package com.zhq.blog.manage.domain.controller.money;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Base64;






import java.util.Date;
import java.util.Random;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhq.blog.core.domain.money.BusinessMan;
import com.zhq.blog.core.domain.money.Card;
import com.zhq.blog.core.domain.money.CardRecord;
import com.zhq.blog.core.domain.money.CreateCard;
import com.zhq.blog.core.domain.search.Addcard;
import com.zhq.blog.core.domain.search.CreateCardSearch;
import com.zhq.blog.manage.domain.controller.BaseController;
import com.zhq.blog.manage.domain.controller.BossModel;

@Controller
@Scope("prototype")
@RequestMapping("/admin/money/createCard/*")
public class CreateCardController extends BaseController {
	
	/*@RequestMapping()
    public BossModel index(@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		return createModel("createCard/list").add("createCardPage",context.getCreateCardRepository().findAll(pageable));
	}*/
	
	@RequestMapping()
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{
		CreateCardSearch search = null;
		if (viewState != null && !viewState.trim().equals("")) {
			search = (CreateCardSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), CreateCardSearch.class);
			return createModel("admin/money/createCard/list")
					.add("createCardSearch", search)
					.add("viewState", viewState)
					.add("cards", context.getCardRepository().findAll())
					.add("createCardPage",context.getCreateCardRepository().findAll(new CreateCard().selectCondition(search),pageable));
		} else {
			search = new CreateCardSearch();
			return createModel("admin/money/createCard/list").add("createCardSearch", search).add("cards", context.getCardRepository().findAll()).add("viewState", "").add("createCardPage", context.getCreateCardRepository().findAll(new CreateCard().selectCondition(search),pageable));

		}
	}
	
	@RequestMapping(value = "index", method = RequestMethod.POST)
	public BossModel index(CreateCardSearch search,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE, sort = "createdDate", direction = Sort.Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {
		return createModel("admin/money/createCard/list")
				.add("createCardPage", context.getCreateCardRepository().findAll(new CreateCard().selectCondition(search),pageable))
				.add("viewState",Base64.getEncoder().encodeToString(JSONObject.fromObject(search).toString().getBytes("UTF-8"))).add("cards", context.getCardRepository().findAll());
	}
	
	
	@RequestMapping(value="add")
	public BossModel add(){
		return createModel("admin/money/createCard/info").add("addcard", new Addcard()).add("cards", context.getCardRepository().findAll()).add("businessMan", context.getBusinessManRepository().findAll());
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final Addcard addcard, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectcreateCard,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		BusinessMan man =  context.getBusinessManRepository().findOne(Long.valueOf(addcard.getBusinessManId()));
		Card card = context.getCardRepository().findOne(Long.valueOf(addcard.getCardId()));
		
		CreateCard cards;
		//数字
		if(card.getRandom_type() == 1){
			for (int i = 0; i < Integer.valueOf(addcard.getNums()); i++) {
				cards = new CreateCard();
				if(card.getCard_head() != null){
					cards.setCard_num(card.getCard_head()+getRandomMethod1(card.getRandom_num()));
				}else{
					cards.setCard_num(getRandomMethod1(card.getRandom_num()));
				}
				cards.setCard_password(getRandomMethod1(card.getRandom_num()));
				getRandomMethod1(card.getRandom_num());
				cards.setCardId(card.getId());
				cards.setBusinessManId(man.getId());
				cards.setStatus(0);
				context.getCreateCardRepository().save(cards);
			}
		}
		//数字+大写字母
		if(card.getRandom_type() == 2){
			for (int i = 0; i < Integer.valueOf(addcard.getNums()); i++) {
				cards = new CreateCard();
				if(card.getCard_head() != null){
					cards.setCard_num(card.getCard_head()+getRandomMethod2(card.getRandom_num()));
				}else{
					cards.setCard_num(getRandomMethod2(card.getRandom_num()));
				}
				cards.setCard_password(getRandomMethod2(card.getRandom_num()));
				getRandomMethod1(card.getRandom_num());
				cards.setCardId(card.getId());
				cards.setBusinessManId(man.getId());
				cards.setStatus(0);
				context.getCreateCardRepository().save(cards);
			}
		}
		//数字+大写字母+小写字母
		if(card.getRandom_type() == 3){
			for (int i = 0; i < Integer.valueOf(addcard.getNums()); i++) {
				cards = new CreateCard();
				if(card.getCard_head() != null){
					cards.setCard_num(card.getCard_head()+getRandomMethod3(card.getRandom_num()));
				}else{
					cards.setCard_num(getRandomMethod3(card.getRandom_num()));
				}
				cards.setCard_password(getRandomMethod3(card.getRandom_num()));
				getRandomMethod1(card.getRandom_num());
				cards.setCardId(card.getId());
				cards.setBusinessManId(man.getId());
				cards.setStatus(0);
				context.getCreateCardRepository().save(cards);
			}
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		CardRecord cardRecord = new CardRecord();
		cardRecord.setCardType("手动");
		cardRecord.setOrder_no(df.format(new Date()).toString());
		cardRecord.setUserName(man.getName());
		cardRecord.setPrice(card.getPrice());
		cardRecord.setNums(Long.valueOf(addcard.getNums()));
		context.getCardRecordRepository().save(cardRecord);
		
		return createModel("redirect:/admin/money/createCard/index");
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		context.getCreateCardRepository().delete(id);
		return createModel("admin/money/createCard/createCard_table").add("createCardPage",context.getCreateCardRepository().findAll(pageable));
	}
	
	//生成随机数字和大小寫字母,
			public static String getRandomMethod3(int length) {
				
				String val = "";
				Random random = new Random();
				
				//参数length，表示生成几位随机数
				for(int i = 0; i < length; i++) {
					
					String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
					//输出字母还是数字
					if( "char".equalsIgnoreCase(charOrNum) ) {
						//输出是大写字母还是小写字母
						int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
						val += (char)(random.nextInt(26) + temp);
					} else if( "num".equalsIgnoreCase(charOrNum) ) {
						val += String.valueOf(random.nextInt(10));
					}
				}
				return val;
			}
			//生成随机数字,
			public static String getRandomMethod1(int length) {
				String val = "";
				Random random = new Random();
				//参数length，表示生成几位随机数
				for(int i = 0; i < length; i++) {
					val += String.valueOf(random.nextInt(10));
				}
					return val;
			}
			
			//生成随机数字和大小寫字母,
					public static String getRandomMethod2(int length) {
						
						String val = "";
						Random random = new Random();
						
						//参数length，表示生成几位随机数
						for(int i = 0; i < length; i++) {
							
							String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
							//输出字母还是数字
							if( "char".equalsIgnoreCase(charOrNum) ) {
								//输出是大写字母还是小写字母
								int temp = 65;
								val += (char)(random.nextInt(26) + temp);
							} else if( "num".equalsIgnoreCase(charOrNum) ) {
								val += String.valueOf(random.nextInt(10));
							}
						}
						return val;
					}
	

}
